package com.lesserpand.springcloudalibabacore.config.rabbitmq.utils;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ProviderUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(ProviderUtils.class);

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送消息
     *
     * @param exchange  队列交换
     * @param routerKey 队列交换绑定的路由键
     */
    public void send(String exchange, String routerKey, String message) {
        CorrelationData correlationId = new CorrelationData(message);
        rabbitTemplate.convertAndSend(exchange, routerKey, message, correlationId);
    }

    /**
     * 发送延迟消息
     *
     * @param messageContent 消息内容
     * @param exchange       队列交换
     * @param routerKey      队列交换绑定的路由键
     * @param delayTimes     延迟时长，单位：毫秒
     */
    public void sendMessage(Object messageContent, String exchange, String routerKey, final long delayTimes) {
        if (!StringUtils.isEmpty(exchange)) {
            LOGGER.info("消息内容：{}", delayTimes, routerKey, JSON.toJSONString(messageContent));
            // 执行发送消息到指定队列，查看源码可知，消息默认持久化。关键源代码：convertMessageIfNecessary，message。如果消息不需要持久化，直接调用send()发送消息。
            // 跟着源码可知，这里默认设置信道为Confirm
            rabbitTemplate.convertAndSend(exchange, routerKey, messageContent, message -> {
                // 设置延迟毫秒值
                message.getMessageProperties().setExpiration(String.valueOf(delayTimes));
                return message;
            });
        } else {
            LOGGER.error("未找到队列消息：{}，所属的交换机", exchange);
        }
    }
}
